package com.demon.framework.boot.autoconfigure;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.util.ObjectUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Web 应用 自动注入配置
 *
 * @author Demon-HY
 * @date 2020-7-23
 */
@Configuration
@Slf4j
public class WebAutoConfiguration {

    @Value("${server.cors.domain:*}")
    private String serverCorsDomain;

    /**
     * 设置支持跨域请求
     */
    @Bean
    @ConditionalOnProperty(prefix = "server.cors", name = "enabled", matchIfMissing = true)
    public FilterRegistrationBean corsFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();

        {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration() {
                @Override
                public String checkOrigin(String requestOrigin) {

                    if (StringUtils.isBlank(requestOrigin)) {
                        return null;
                    }
                    if (ObjectUtils.isEmpty(this.getAllowedOrigins())) {
                        return null;
                    }

                    if (this.getAllowedOrigins().contains(ALL)) {
                        if (!this.getAllowCredentials()) {
                            return ALL;
                        } else {
                            return requestOrigin;
                        }
                    }
                    //FIXME 重写 域名匹配方式,支持通配 ，eg: *.demon.com
                    for (String allowedOrigin : this.getAllowedOrigins()) {
                        if (requestOrigin.endsWith(allowedOrigin)) {
                            return requestOrigin;
                        }
                    }

                    return null;
                }
            };
            config.setAllowCredentials(true);
            //设置允许的域名
            String[] split = StringUtils.split(serverCorsDomain, ",");
            if (null != split) {
                for (String domain : split) {
                    config.addAllowedOrigin(domain);
                }
            }

            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);


            registration.setFilter(new CorsFilter(source));
        }

        registration.addUrlPatterns("/*");
        registration.setName("Cors-Filter");
        //设置过滤器 优先级最高
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE);
        log.info("初始化CORS 过滤器完成。。。");
        return registration;
    }
}
